<!-- 创建登录页面 -->
<template>
    <div class="login-container">
        <div class="login-form">
            <div class="form-header">
                <h2>登录</h2>
                <el-button type="text" @click="toggleForm">
                    去注册
                </el-button>
            </div>

            <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" @submit.prevent="submitForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" native-type="submit">
                        登录
                    </el-button>
                </el-form-item>
                <!-- <el-form-item label="图片" prop="img">
                    <el-upload name="img" action="https://jsonplaceholder.typicode.com/posts/" :on-success="uploadImg"
                        :file-list="[]" :before-upload="validateImg">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div style="margin-top: 10px"></div>
                        </el-upload>
                </el-form-item> -->
                上传图片
                <el-form-item label="图片" prop="img">
                    <el-upload name="img" action="https://jsonplaceholder.typicode.com/posts/" :on-success="uploadImg"
                        :file-list="[]" :before-upload="validateImg">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div style="margin-top: 10px">
                            <el-tooltip content="只能上传图片格式文件" placement="top">
                                <el-icon type="question-circle-o"></el-icon>
                            </el-tooltip>
                        </div>
                    </el-upload>
                </el-form-item>

                <!-- <el-button type="text" @click="toggleForm"> 
                    去注册
                </el-button> -->
            </el-form>
        </div>
    </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';

export default {
    name: 'UserLogin',
    setup() {
        const store = useStore();
        const router = useRouter();
        const formRef = ref(null);
        const isLogin = ref(true);

        const form = reactive({
            username: '',
            password: '',
        });
        //校验
        const validateImg = (rule, value, callback) => {
            const imgType = ['jpg', 'jpeg', 'png', 'gif'];
            const imgName = value.name.split('.').pop().toLowerCase();
            if (!imgType.includes(imgName)) {
                callback(new Error('请上传图片格式文件!'));
            } else {
                callback();
            }
        };

        const toggleForm = () => {
            isLogin.value = !isLogin.value;
        };

        const submitForm = () => {
            formRef.value.validate((valid) => {
                if (valid) {
                    const username = form.username;
                    const password = form.password;
                    const img = form.img;
                    if (login(username, password)) {
                        store.dispatch('user/login', { username, password, img });
                        router.push('/');
                    }
                } else { }
            })
        }


        const rules = reactive({
            username: [
                { required: true, message: '请输入用户名', trigger: 'blur' },
                { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' },
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'blur' },
                { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
            ],
        });
        // 自定义验证器
        const validateUsername = (rule, value, callback) => {
            if (value === 'admin') {
                //         callback(new Error('用户名已被占用!'));
                callback();
            } else {
                callback();
            }
        };
        // 时间戳格式化
        const getCurrentTime = () => {
            const date = new Date();
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const hours = date.getHours();
            const minutes = date.getMinutes();
            const seconds = date.getSeconds();
            const time = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            return time;
            console.log(time); // 2022-03-16 10:20:30
        };
        // 登录
        const login = (username, password) => {
            const time = getCurrentTime();
            console.log(`登录时间: ${time}`);
            console.log(`用户名: ${username}`);
            console.log(`密码: ${password}`);
            return true;
        };
        // validateUsername 自定义验证器
        const validateUsername = (rule, value, callback) => {
            if (value === 'admin') {
                //         callback(new Error('用户名已被占用!'));
                callback();
            } else {
                callback();
            }
        };

        const validatePassword = (rule, value, callback) => {
            if (value !== form.password) {
                callback(new Error('两次输入的密码不一致!'));
            } else {
                callback();
            }
        };
        // 自定义验证器
        rules.username.push({ validator: validateUsername, trigger: 'blur' });
        rules.password.push({ validator: validatePassword, trigger: 'blur' });

        // 验证图片格式
        const validateImg = (rule, value, callback) => {
            const imgType = ['jpg', 'jpeg', 'png', 'gif'];
            const imgName = value.name.split('.').pop().toLowerCase();
            if (!imgType.includes(imgName)) {
                callback(new Error('请上传图片格式文件!'));
            } else {
                callback();
            }
        };
        // // 图片上传
        // const uploadImg = (file) => {
        //     const imgUrl = URL.createObjectURL(file);
        //     console.log(imgUrl);
        //     return true;
        // };

        // 上传图片
        const uploadImg = (file) => {
            const imgUrl = URL.createObjectURL(file);
            console.log(imgUrl);
            return true;
        };


        // 表单提交
        const submitForm = () => {
            formRef.value.validate((valid) => {
                if (valid) {
                    const username = form.username;
                    const password = form.password;
                    const img = form.img;
                    if (login(username, password)) {
                        if (uploadImg(img)) {
                            alert('登录成功!');
                            router.push({ path: '/' });
                        }
                    }
                }
            });
        };


        const toggleForm = () => {
            isLogin.value = !isLogin.value;
            formRef.value?.resetFields();
        };

        const submitForm = () => {
            formRef.value.validate((valid) => {
                if (valid) {
                    store.dispatch('user/login', form).then(() => {
                        router.push({ path: '/' });
                    });
                }
            });
        };

        return {
            form,
            rules,
            formRef,
            isLogin,
            toggleForm,
            submitForm,
        };
    },
};
</script>


<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
}

.login-form {
    width: 300px;
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.form-header h2 {
    font-size: 24px;
    font-weight: bold;
}

.el-form-item {
    margin-bottom: 20px;
}

.el-input {
    width: 100%;
}

.el-button {
    width: 100%;
}
</style>